package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.api.feign.ApArticleFeignClient;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SyncArticleListener {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApArticleFeignClient apArticleFeignClient;


    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = ArticleConstants.ARTICLE_ES_SYNC_QUEUE, durable = "true"),
                    exchange = @Exchange(name = ArticleConstants.ARTICLE_ES_SYNC_TOPIC, type = ExchangeTypes.TOPIC),
                    key = ArticleConstants.ARTICLE_ES_SYNC_ROUTINGKEY
            )
    )
    public void getMessage(String message){

        //1.根据文章id查询文章相关信息
        ResponseResult articleMsg = apArticleFeignClient.getArticleMsg(message);

        String jsonStr = (String) articleMsg.getData();

        ApArticle apArticle = JSON.parseObject(jsonStr, ApArticle.class);

        //如果文章不是下架就在es中添加该组数据
        if(apArticle.getIsDown() == 0 && apArticle.getIsDelete() ==0) {
            //创建请求对象
            IndexRequest request = new IndexRequest("app_info_article").id(apArticle.getId().toString());

            //添加请求参数
            String jsonString = JSON.toJSONString(apArticle);
            request.source(jsonString, XContentType.JSON);

            //发送请求
            try {
                client.index(request, RequestOptions.DEFAULT);
                return;
            } catch (IOException e) {
                e.getStackTrace();
            }
        }

            //文章下架或者删除就移除es给文档
            DeleteRequest request = new DeleteRequest("app_info_article").id(apArticle.getId().toString());

            try {
                client.delete(request,RequestOptions.DEFAULT);
            }catch (IOException e){
                e.getStackTrace();
            }
        }
    }
